package com.kmist.xiakexing.adapter;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class ViewHolder extends RecyclerView.ViewHolder {

    private final Context mContext;
    private final View mConvertView;
    private SparseArray<View> mViews = null;

    public ViewHolder(Context context, @NonNull View itemView, ViewGroup parent) {
        super(itemView);
        mContext = context;
        mConvertView = itemView;
        mViews = new SparseArray<View>();
    }

    public static ViewHolder get(Context context, ViewGroup parent, int layoutId){
        View itemView = LayoutInflater.from(context).inflate(layoutId,parent,false);
        ViewHolder holder = new ViewHolder(context, itemView, parent);
        return holder;
    }

    public  <T extends View>T getView(int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    public ViewHolder setText(int viewId, String text){
        TextView tv = getView(viewId);
        tv.setText(text);
        if(text.equals("")){
            tv.setVisibility(View.INVISIBLE);
        }else{
            tv.setVisibility(View.VISIBLE);
        }
        return this;
    }

    public ViewHolder appendText(int viewId, String text){
        TextView tv = getView(viewId);
        tv.append(text);
        return this;
    }

    public ViewHolder setTextColor(int viewId, int textColor){
        TextView tv = getView(viewId);
        tv.setTextColor(textColor);
        return this;
    }

    public ViewHolder setOnClickListener(int viewId, View.OnClickListener listener){
        View view = getView(viewId);
        view.setOnClickListener(listener);
        return this;
    }

}
